const Router = require('koa-router')
const router = new Router;
const versionData = require('./version.json')
const fs = require('fs');
const path = require('path');
const parsePostData = require('./body-parser');

router.get('/version', (ctx, next) => {
  ctx.body = {
    code: 0,
    data: {
      version: versionData.version
    }
  }
})

router.get('/wgt', (ctx, next) => {
  ctx.body = {
    code: 0,
    data: {
      path: 'http://124.221.150.29:8002/xiuxian.wgt'
    }
  }
})

const mapFolder = path.join(__dirname, '../src/js/game/maps/defines');

function getTime(){
  let date = new Date();

  return `${date.getFullYear()}-${date.getMonth()}-${date.getDay()}`;
}

router.post('/map/save', async (ctx, next) => {
  if(ctx.headers.host.indexOf('localhost') <= -1) {
    ctx.body = {
      code: 422,
      data: '非可用环境'
    }
    return;
  }

  const mapData = require('../src/js/game/maps/defines/map.json');
  fs.writeFileSync(path.join(mapFolder, `mapV${mapData.version}-${new Date().getTime()}.json`), JSON.stringify(mapData));
  
  let data = await parsePostData( ctx );
  fs.writeFileSync(path.join(mapFolder, `map.json`), JSON.stringify({
    "version": data.version,
    "created_time": new Date(),
    "data": data.mapData,
  }));

  ctx.body = {
    code: 0,
    data: 'success'
  }
})

module.exports = router;